const jwt = require('jsonwebtoken');
const userService = require('../services/user');
const typeService = require('../services/type');
const {SECRET} = require('../config/config');

class UserController {

  async register(req, res) {
    const defaultAvatar = 'http://s.yezgea02.com/1615973940679/WeChat77d6d2ac093e247c361f0b8a7aeb6c2a.png';
    const defaultSignature = '世界和平'
    let { username, password, signature = defaultSignature, avatar } = req.body;
    
    if (!username || !password) {
      return res.send({ 'state': 2, 'info': '用户名或密码不能为空' });
    }

    const userInfo = await userService.getUserName(username);

    if (userInfo && userInfo._id) {
      return res.send({ 'state': 1, 'info': '用户名已被注册，请重新输入' });
    }
    if(!avatar) avatar = defaultAvatar 
    const result = await userService.register({
      username,
      password,
      signature,
      avatar,
      alive: true
    });

    if (result) {
      const user_id = result._id.toString()
      const type_result = await typeService.setDefaultType(user_id)
      if(type_result)
        return res.send({ 'state': 0, 'info': '用户创建成功' });
    }
    return res.send({ 'state': 2, 'info': '系统错误，请联系后台管理员' });
  }

  async login(req, res) { 
    let { username, password, expire=1 } = req.body;
    if (!username || !password) {
      return res.send({ 'state': 4, 'info': '用户名或密码不能为空' });
    }
    const userInfo = await userService.getUserName(username);
    if (!userInfo) 
      return res.send({ 'state': 1, 'info': '用户名不存在，请检查用户名或注册新的账户' });
    if (userInfo && userInfo.password !== password) 
      return res.send({ 'state': 2, 'info': '密码错误' });
    if (userInfo && userInfo.alive == false) 
      return res.send({ 'state': 3, 'info': '账户已注销，想恢复账户请联系系统管理员' })
    const token = 'Bearer ' + jwt.sign(
      {
        _id: userInfo._id,
        username: userInfo.username
      },
      SECRET, { expiresIn: Number(expire) * 3600 * 24 }
    ) 
    res.send({'state': 0, token})
  }
  async info(req, res) {
    const userInfo = await userService.getUserName(req.user.username);
    if (userInfo) {
      res.send(
        {
          "state": 0,
          "info": {
            _id: userInfo._id,
            username: userInfo.username,
            signature: userInfo.signature || '',
            avatar: userInfo.avatar || defaultAvatar
          }
        }
      )
    }
    else {
      res.send({ 'state': 1, 'info': '获取用户信息错误，请联系后台管理员' });
    }
  }
  async cancel(req, res) {
    let { username, password } = req.body;
    const userInfo = await userService.getUserName(username);
    if (!userInfo) 
      return res.send({ 'state': 1, 'info': '用户名不存在，请检查用户名' });
    if (userInfo && userInfo.password !== password) 
      return res.send({ 'state': 2, 'info': '密码错误，无法销毁账户' });
    userInfo.alive = false
    const result = await userService.cancel({userInfo});
    if (result) {
      return res.send({ 'state': 0, 'info': '账户注销成功' });
    }
    else
      return res.send({ 'state': 3, 'info': '注销错误，请联系后台管理员' });
  }

  async edit(req, res) {
    const { username, password, signature, avatar } = req.body;
    let userInfo = null;
    // 传了用户名，且和token中的不一样
    if (username && req.user.username !== username) {
      userInfo = await userService.getUserName(username);
      if(userInfo && userInfo._id) return res.send({ 'state': 2, 'info': '用户名已被注册，请重新输入' });
    }
    userInfo = await userService.getUserName(req.user.username);
    if(!userInfo) return res.send({ 'state': 3, 'info': '用户名修改后需重新登录' });

    if (username) userInfo.username = username
    if (password) userInfo.password = password
    if (signature) userInfo.signature = signature
    if (avatar) userInfo.avatar = avatar
    const result = await userService.edit(userInfo);
    if (result) {
      return res.send({ 'state': 0, 'info': '信息更新成功' });
    }
    else
      return res.send({ 'state': 1, 'info': '信息更新错误，请联系后台管理员' });
  }
}

// 导出 Controller 的实例
module.exports = new UserController();
